package com.quan.sdk.weixin.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.mzlion.easyokhttp.HttpClient;
import com.quan.sdk.weixin.constant.API;
import com.quan.sdk.weixin.enums.JsApiType;
import com.quan.sdk.weixin.model.JsTicket;
import com.quan.sdk.weixin.utils.WeixinContext;

/**
 * 定时获取JSSDK票据，每个1小时55分获取一次
 * @author yhaoquan
 *
 */
@Component
public class JsApiTicketRefreshTask {
	
	private static Logger logger = LoggerFactory.getLogger(JsApiTicketRefreshTask.class);

	/**
	 * 0/5 * * * * ? 	  每5秒执行一次
	 * 0 55 0/1 * * ?	 每个1小时55分获取一次
	 */
	@Scheduled(cron = "0 55 0/1 * * ?")
	public void accessJsApiTicketRefreshJob() {
		JsTicket jsTicket = getJsTicket(JsApiType.jsapi) ;
		WeixinContext.setJsApiTicket(jsTicket.getTicket());
	}
	
	public static JsTicket getJsTicket(JsApiType jsApiType) {
		String url = API.get(API.JS_API_TICKET_URL, WeixinContext.getAccessToken(), null == jsApiType ? JsApiType.jsapi.name() : jsApiType.name()) ;
		
		JsTicket ticket = HttpClient.get(url).execute().asBean(JsTicket.class) ;
		
		if(ticket.getErrcode() > 0) {
			logger.error("微信JsApi-Ticket票据获取[失败]：{}", ticket.getErrmsg());
		} else {
			logger.info("微信JsApi-Ticket票据获取[成功]:{}", ticket);
		}
		return ticket ;
	}
}
